java


Loops are essential in any programming language — they help us repeat tasks without writing redundant code. In Java, loops become even more powerful when we add break, continue, and nested loops into the mix. In this post, we’ll walk through: What break and continue do How they differ How to use them in nested loops Code examples to help you understand

The Basics: Loops in Java Before diving into break and continue, here’s a quick refresher on loop types in Java: for loop while loop do...while loop Each lets you repeat a block of code as long as a certain condition holds true. 🛑 break Statement The break statement immediately exits the loop (or switch statement) where it's placed. ✅ Example:

for (int i = 1; i <= 10; i++) {
    if (i == 5) {
        break;
    }
    System.out.println(i);
} 

continue Statement

The continue statement skips the current iteration and moves to the next one.

for (int i = 1; i <= 5; i++) {
    if (i == 3) {
        continue;
    }
    System.out.println(i);
} 

Nested Loops in Java

A nested loop means a loop inside another loop — commonly used for working with matrices or multi-dimensional arrays.

for (int i = 1; i <= 3; i++) {
    for (int j = 1; j <= 3; j++) {
        System.out.println("i = " + i + ", j = " + j);
    }
} 

Using break in Nested Loops

Using break in a nested loop only breaks the innermost loop by default.

for (int i = 1; i <= 3; i++) {
    for (int j = 1; j <= 3; j++) {
        if (j == 2) {
            break;
        }
        System.out.println("i = " + i + ", j = " + j);
    }
} 

Using continue in Nested Loops

Similarly, continue only affects the innermost loop unless you use labels (which we’ll cover next).

for (int i = 1; i <= 3; i++) {
    for (int j = 1; j <= 3; j++) {
        if (j == 2) {
            continue;
        }
        System.out.println("i = " + i + ", j = " + j);
    }
}


break --> Exits the loop completely

continue --> Skips current iteration